//
//  PhoneVerifyViewController.m
//  RENTVISITOR
//
//  Created by wonder on 2017/8/28.
//  Copyright © 2017年 UNN. All rights reserved.
//

#import "PhoneVerifyViewController.h"
#import "RentVieitor.h"
#import "EditPhoneViewController.h"
#import "SetPassWordViewController.h"
#import "ChangeEmailViewController.h"

@interface PhoneVerifyViewController ()

@end

@implementation PhoneVerifyViewController {
    
    UIButton *getButton;
    NSInteger getcodeTime;
    UITextField *phoneField;
    BOOL isVerify;
    NSString *auth;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    isVerify = NO;
    self.title = @"填写验证码";
    self.view.backgroundColor = BackgroundColor;
    [self creatLeftView];
    [self creatView];
}


- (void)creatLeftView {
    
    // 自定义导航栏左侧按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 80,15 );
    [leftBtn setImage:[UIImage imageNamed:@"箭头左"] forState:UIControlStateNormal];
    [leftBtn setTitle:@"返回" forState:UIControlStateNormal];
    leftBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [leftBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
    leftBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [leftBtn setTitleColor:[Utils colorConvertFromString:@"#333333"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    // 自定义导航栏左侧按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    rightBtn.frame = CGRectMake(0, 0, 50, 20);
    [rightBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor colorWithRed:225/255.0 green:141/255.0 blue:43/255.0 alpha:1] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;

    
}

- (void)creatView {
    
    
    UILabel *proLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, KWidth, 50)];
    proLabel.text = @"短信验证码已发送,请填写验证码";
    proLabel.textColor = [Utils colorConvertFromString:@"#666666"];
    proLabel.font = [UIFont systemFontOfSize:18];
    proLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:proLabel];
    
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 50, KWidth, 100)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteView];
    
    UILabel *phoneLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 50, 30)];
    phoneLabel.text = @"手机号";
    phoneLabel.textAlignment = NSTextAlignmentLeft;
    phoneLabel.font = [UIFont systemFontOfSize:15];
    phoneLabel.textColor = [Utils colorConvertFromString:@"#101010"];
    [whiteView addSubview:phoneLabel];
    
    getButton = [UIButton buttonWithType:UIButtonTypeSystem];
    getButton.frame = CGRectMake(KWidth-100, 10, 80, 30);
    [getButton setTitleColor:[UIColor colorWithRed:99/255.0 green:99/255.0 blue:99/255.0 alpha:1] forState:UIControlStateNormal];
    [getButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [getButton addTarget:self action:@selector(getNumber) forControlEvents:UIControlEventTouchUpInside];
    [whiteView addSubview:getButton];
    
    UILabel *codeLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 60, 50, 30)];
    codeLabel.text = @"验证码";
    codeLabel.textAlignment = NSTextAlignmentLeft;
    codeLabel.font = [UIFont systemFontOfSize:15];
    codeLabel.textColor = [Utils colorConvertFromString:@"#101010"];
    [whiteView addSubview:codeLabel];
    
    UILabel *numLabel = [[UILabel alloc] initWithFrame:CGRectMake(120, 10, KWidth-120-80, 30)];
    numLabel.text = self.phone;
    numLabel.textAlignment = NSTextAlignmentLeft;
    numLabel.font = [UIFont systemFontOfSize:15];
    numLabel.textColor = [Utils colorConvertFromString:@"#101010"];
    [whiteView addSubview:numLabel];
    
    //分割线
    CALayer *MlineLayer = [CALayer layer];
    MlineLayer.backgroundColor = [[Utils colorConvertFromString:@"#cfcfcf"] CGColor];
    MlineLayer.frame = CGRectMake(20 ,49, KWidth-40, 1);
    [whiteView.layer addSublayer:MlineLayer];
    
    phoneField = [[UITextField alloc] initWithFrame:CGRectMake(120, 60, KWidth-120, 30)];
    phoneField.placeholder = @"请输入验证码";
    phoneField.textColor = [Utils colorConvertFromString:@"#101010"];
    phoneField.font = [UIFont systemFontOfSize:13];
    [whiteView addSubview:phoneField];
    
    UIButton *changeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    changeBtn.frame = CGRectMake(30,150+30, KWidth-60, 40);
    [changeBtn setBackgroundColor:[UIColor colorWithRed:249/255.0 green:105/255.0 blue:39/255.0 alpha:1]];
    [changeBtn setTitle:@"提交" forState:UIControlStateNormal];
    [changeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    changeBtn.layer.masksToBounds = YES;
    [changeBtn addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchUpInside];
    changeBtn.layer.cornerRadius = 2;
    [self.view addSubview:changeBtn];
    
//    UIButton *userButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    userButton.frame = CGRectMake( 30, 150+30+50, KWidth-60 ,30);
//    [userButton setTitleColor:[Utils colorConvertFromString:@"#305782"] forState:UIControlStateNormal];
//    userButton.titleLabel.font = [UIFont systemFontOfSize:13];
//   
//    [userButton setBackgroundColor:[UIColor clearColor]];
//    [userButton setTitle:@"收不到验证码" forState:UIControlStateNormal];
//    [userButton addTarget:self action:@selector(getCodeAction) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:userButton];

}

- (void)nextAction {
    
    //修改密码
    if (isVerify == NO || auth == nil) {
        
        [APPDELEGATE showPro:@"请进行手机验证"];
        return;
    }
    
    if (self.type == 1) {
        
        //更改密码
        SetPassWordViewController *passVc = [[SetPassWordViewController alloc] init];
        passVc.auth = auth;
        [self.navigationController pushViewController:passVc animated:YES];
        return;
    }
   
    if (self.type == 2) {
        
        //更改绑定电话
        EditPhoneViewController *editvc = [[EditPhoneViewController alloc] init];
        editvc.phone = self.phone;
        editvc.auth = auth;
        [self.navigationController pushViewController:editvc animated:YES];
        return;
    }
    
    if (self.type == 3) {
        
        ChangeEmailViewController *emailVc = [[ChangeEmailViewController alloc] init];
        emailVc.auth = auth;
        emailVc.email = self.email;
        [self.navigationController pushViewController:emailVc animated:YES];
    }
    
//    if (isVerify == YES & auth != nil) {
//        
//        if (self.type == 1) {
//            
//            
//            
//        }else if (self.type == 2) {
//            
    
//
//        }else if (self.type ==3) {
//            
//            
//            
//        }
//        
//        
//    }else {
//        
//        [APPDELEGATE showPro:@"请进行手机验证"];
//    }
    
}

//获取验证码
- (void)getNumber {
    
    getButton.enabled = NO;
    getcodeTime = 60;
    [getButton setTitle:[NSString stringWithFormat:@"%ld",(long)getcodeTime] forState:UIControlStateDisabled];
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(getCodeBtnTimerOut:) userInfo:nil repeats:YES];
    
    NSDictionary *dataDic = User_listsValue;
    NSString *number = dataDic[@"number"];
    NSString *token = dataDic[@"token"];
    NSString *urlstr= [NSString stringWithFormat:@"%@member/auth/sendsms",Main_Url];
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@%@",number,token,APPKEY_URL,urlstr];
    //32位小写
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    md5String = [md5String stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSDictionary *param = @{
                            @"number":number,
                            @"token":token,
                            @"sign":md5String
                            };
    AFHTTPSessionManager *manger=[AFHTTPSessionManager manager];
    manger.responseSerializer=[AFHTTPResponseSerializer serializer];
    [manger POST:urlstr parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        

        NSDictionary* jsonDic = [NSJSONSerialization
                                 JSONObjectWithData:responseObject
                                 options:kNilOptions
                                 error:nil];
        
        if ([jsonDic[@"code"] isEqualToString:@"10000"]) {
            
           
            
        }else {
            
            [APPDELEGATE showPro:jsonDic[@"message"]];
            getButton.enabled = YES;
            [getButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        getButton.enabled = YES;
        [APPDELEGATE showPro:@"网络错误"];
    }];
    
    
    
}

//提交认证
- (void)submitAction {
    
    [self.view endEditing:YES];
    if (phoneField.text.length == 0) {
        
        [APPDELEGATE  showPro:@"请输入验证码"];
    }
    NSDictionary *dataDic = User_listsValue;
    NSString *number = dataDic[@"number"];
    NSString *token = dataDic[@"token"];
    NSString *urlstr= [NSString stringWithFormat:@"%@member/auth/verify",Main_Url];
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@%@%@",number,phoneField.text,token,APPKEY_URL,urlstr];
    //32位小写
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    md5String = [md5String stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSDictionary *param = @{
                            @"number":number,
                            @"token":token,
                            @"smscode":phoneField.text,
                            @"sign":md5String
                            };
    AFHTTPSessionManager *manger=[AFHTTPSessionManager manager];
    manger.responseSerializer=[AFHTTPResponseSerializer serializer];
    [manger POST:urlstr parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        NSDictionary* jsonDic = [NSJSONSerialization
                                 JSONObjectWithData:responseObject
                                 options:kNilOptions
                                 error:nil];
        
        if ([jsonDic[@"code"] isEqualToString:@"10000"]) {
            
            NSDictionary *dataDic = jsonDic[@"data"];
            auth = dataDic[@"auth"];
            isVerify = YES;
            [APPDELEGATE showEditSuccess:@"验证成功"];
            
        }else {
            
            [APPDELEGATE showPro:jsonDic[@"message"]];
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        getButton.enabled = YES;
        [APPDELEGATE showPro:@"网络错误"];
    }];
}

#pragma mark - 时间倒计时
- (void) getCodeBtnTimerOut:(NSTimer *)timer{
    
    getcodeTime--;
    if (getcodeTime > 0) {
        [getButton setTitle:[NSString stringWithFormat:@"%ld",(long)getcodeTime] forState:UIControlStateDisabled];
    }else{
        
        getButton.enabled = YES;
        [getButton setTitle:@"重获验证码" forState:UIControlStateNormal];
        [timer invalidate];
    }
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view endEditing:YES];
}
////重新获取验证码
//- (void)getCodeAction {
//    
//    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//    UIAlertAction *aginAction = [UIAlertAction actionWithTitle:@"重新获取验证码" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        
//        
//    
//    }];
//
//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        
//    }];
//    
//    [alertVC addAction:aginAction];
//    [alertVC addAction:cancelAction];
//    [self presentViewController:alertVC animated:YES completion:NULL];
//}



- (void)backAction {
    [self.navigationController popViewControllerAnimated:YES];
}
@end
